package cn.ilikes.modules.likes.modules.folders.impls;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.ilikes.modules.likes.dbs.IlikesFolder;
import cn.ilikes.modules.likes.dbs.IlikesUser;
import cn.ilikes.modules.likes.modules.IlikesHbaseService;
import cn.ilikes.modules.likes.modules.folders.IilikesFolderService;
import cn.ilikes.modules.likes.modules.folders.IilikesMylikesException;
import cn.ilikes.modules.likes.modules.users.IUserService;
import cn.ilikes.modules.likes.modules.users.IlikesUserException;

@Component(IilikesFolderService.SPRING_SERVICE)
public class IilikesFolderServiceImpls implements IilikesFolderService {

	@Resource(name = IlikesHbaseService.SPRING_SERVICE)
	private IlikesHbaseService hbaseIlikesService;

	@Resource(name = IUserService.SPRING_SERVICE)
	private IUserService userService;

	@Override
	public void addMyIlikesFolder(String userId, String parentsId, IlikesFolder ilikesFolder) throws IilikesMylikesException {

		try {
			IlikesUser iikesUser = userService.getIlikesUser(userId);
			if (iikesUser == null)
				throw new IilikesMylikesException("not find userId " + userId + " IlikesUser ");
			List<IlikesFolder> ilikesFolders = new ArrayList<IlikesFolder>();
			ilikesFolders.add(ilikesFolder);
			iikesUser.setIlikesFolders(ilikesFolders);
			ilikesFolder.setLikesUser(iikesUser);
			if (parentsId != null) {
				IlikesFolder parentIlikesFolder = hbaseIlikesService.get(parentsId, IlikesFolder.class);
				List<IlikesFolder> childsFolders = new ArrayList<IlikesFolder>();
				childsFolders.add(ilikesFolder);
				parentIlikesFolder.setChilds(childsFolders);
				ilikesFolder.setParents(parentIlikesFolder);

			}
			hbaseIlikesService.save(ilikesFolder);
		} catch (IlikesUserException e) {
			throw new IilikesMylikesException(e);
		}

	}

	@Override
	public List<IlikesFolder> selectTopIlikesFolder(String userId) throws IilikesMylikesException {
		Map<String, Object> values = new HashMap<String, Object>();
		values.put("loginName", userId);
		return hbaseIlikesService.findByNameQuery("select_my_top_folder", values);

	}

	@Override
	public List<IlikesFolder> selectMyIlikesChildfolder(String parentId, String userId) throws IilikesMylikesException {

		Map<String, Object> values = new HashMap<String, Object>();
		values.put("loginName", userId);
		values.put("parentId", parentId);
		return hbaseIlikesService.findByNameQuery("select_my_child_folder_parentId", values);
	}

	@Override
	public IlikesFolder getIlikesFolder(String parentId) throws IilikesMylikesException {

		return hbaseIlikesService.get(parentId, IlikesFolder.class);
	}

	@Override
	public IlikesFolder get(String folderId) throws IilikesMylikesException {
		return hbaseIlikesService.get(folderId, IlikesFolder.class);
	}

}
